/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.hibernate.Session;
import pojo.Nguoidung;
import until.HibernateUtil;

/**
 *
 * @author Alvis
 */
public class NguoiDungDao {

    private Session session;

    public NguoiDungDao() {
        session = HibernateUtil.getSessionFactory().openSession();

    }

    public void Insert(Nguoidung nguoidung) {
        try {
            session.getTransaction().begin();
            // nguoidung.setManguoidung(null);


            String sql1 = "select nextval('nguoidung_manguoidung_seq')";
            Statement st = session.connection().createStatement();
            ResultSet rq = (ResultSet) st.executeQuery(sql1);
            int ma = 0;
            while (rq.next()) {
                ma = rq.getInt("nextval");
            }
            nguoidung.setManguoidung(ma);
            session.save(nguoidung);


            session.flush();
            session.getTransaction().commit();
        } catch (SQLException ex) {
            Logger.getLogger(NguoiDungDao.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public void Update(Nguoidung nguoidung, int id) {
        session.getTransaction().begin();
        Nguoidung ngdung = (Nguoidung) session.get(Nguoidung.class, id);
        ngdung.setHoten(nguoidung.getHoten());
        ngdung.setEmail(nguoidung.getEmail());
        ngdung.setNgaysinh(nguoidung.getNgaysinh());
        ngdung.setDiachi(nguoidung.getDiachi());
        session.update(ngdung);
        // session.flush();
        session.getTransaction().commit();
    }

    public void Delete(int id) {
        session.getTransaction().begin();
        session.delete(session.get(Nguoidung.class, id));
        session.flush();
        session.getTransaction().commit();
    }
}
